package com.innovation.ic.b1b.monitor.base.handler;

import com.google.common.base.Strings;
import com.innovation.ic.b1b.monitor.base.mapper.MongodbAvailableJobLogMapper;
import com.innovation.ic.b1b.monitor.base.mapper.MongodbAvailableJobMapper;
import com.innovation.ic.b1b.monitor.base.mapper.MongodbMapper;
import com.innovation.ic.b1b.monitor.base.model.*;
import com.innovation.ic.b1b.monitor.base.pojo.constant.JobDataMapConstant;
import com.innovation.ic.b1b.monitor.base.pojo.enums.ActiveEnum;
import com.innovation.ic.b1b.monitor.base.value.TimeSetConfig;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoIterable;
import lombok.SneakyThrows;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;
import javax.annotation.Resource;
import java.lang.System;
import java.sql.Date;
import java.util.Random;

/**
 * @desc   mongodb可用任务处理类
 * @author linuo
 * @time   2023年3月24日14:56:29
 */
public class MongodbAvailableJobHandler extends QuartzJobBean {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource
    private HandlerHelper handlerHelper;

    @Resource
    private MongodbMapper mongodbMapper;

    @Resource
    private TimeSetConfig timeSetConfig;

    @Resource
    private MongodbAvailableJobMapper mongodbAvailableJobMapper;

    @Resource
    private MongodbAvailableJobLogMapper mongodbAvailableJobLogMapper;

    @SneakyThrows
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) {
        log.info("开始执行mongodb可用任务处理");

        // 获取1-5间的随机数
        int min = 1;
        int max = 5;
        Random random = new Random();
        int s = random.nextInt(max) % (max - min + 1) + min;
        int sleepTime = s * 1000;
        log.info("休眠[{}]秒", s);
        Thread.sleep(sleepTime);

        JobDataMap jobDataMap = jobExecutionContext.getMergedJobDataMap();
        int id = jobDataMap.getInt(JobDataMapConstant.ID);
        MongodbAvailableJob mongodbAvailableJob = mongodbAvailableJobMapper.selectById(id);
        if(mongodbAvailableJob != null) {
            Mongodb mongodb = mongodbMapper.selectById(mongodbAvailableJob.getMongodbId());
            if (mongodb != null) {
                String mongodbName = mongodb.getName();

                // 存活状态
                Integer active = ActiveEnum.NO.getCode();

                MongodbAvailableJobLog mongodbAvailableJobLog = new MongodbAvailableJobLog();
                mongodbAvailableJobLog.setMongodbAvailableJobId(id);
                mongodbAvailableJobLog.setStartTime(new Date(System.currentTimeMillis()));

                if(Strings.isNullOrEmpty(mongodb.getUri())){
                    String message = mongodbName + "配置信息不完整,无法检测是否存活";
                    log.info(message);
                    mongodbAvailableJobLog.setDescription(message);
                }else{
                    // 判断mongodb是否可用
                    String message = judgeMongodbIfActive(mongodb);
                    if(message == null){
                        active = ActiveEnum.YES.getCode();
                    }else{
                        mongodbAvailableJobLog.setDescription(message);
                    }
                }

                mongodbAvailableJobLog.setActive(active);
                int insert = mongodbAvailableJobLogMapper.insert(mongodbAvailableJobLog);
                if(insert > 0){
                    log.info("mongodb可用任务日志插入成功");

                    if(active.intValue() == ActiveEnum.NO.getCode().intValue()){
                        // 发送邮件
                        String message = mongodbName + "出现异常，原因：" + mongodbAvailableJobLog.getDescription() + "，请查看mongodb状态并及时进行异常处理。";
                        handlerHelper.sendEmail(mongodbAvailableJob.getAlarmEmail(), message, null);
                    }
                }
            }else{
                log.info("未在mongodb表中查询到id=[{}]的配置信息,无法执行监控mongodb可用任务", mongodbAvailableJob.getMongodbId());
            }
        }else{
            log.info("监控mongodb可用任务id为[{}]的数据不存在,无法执行任务", id);
        }
    }

    /**
     * 判断mongodb是否可用
     * @param mongodb mongodb配置信息
     * @return 返回结果
     */
    private String judgeMongodbIfActive(Mongodb mongodb) throws InterruptedException {
        String message = null;
        boolean ifHaveDataBase = Boolean.FALSE;

        MongoClient client = null;

        try {
            log.info("第一次执行监控mongodb是否可用任务");
            MongoClientURI mongoClientUri = new MongoClientURI(mongodb.getUri());
            String database = mongoClientUri.getDatabase();
            client = new MongoClient(mongoClientUri);
            MongoIterable<String> strings = client.listDatabaseNames();
            for(String dataBaseName : strings){
                if(dataBaseName.equals(database)){
                    ifHaveDataBase = Boolean.TRUE;
                    log.info("mongodb连接成功");
                    break;
                }
            }

            if(ifHaveDataBase){
                log.info("mongodb连接成功");
            }else{
                throw new Exception("Mongodb连接失败");
            }
        }catch (Exception e){
            if(client != null){
                client.close();
                client = null;
            }

            log.warn("监控mongodb是否可用任务出现问题,原因:[{}],待{}秒后重试", e.toString(), timeSetConfig.getRetryWaitTime());
            Thread.sleep(timeSetConfig.getRetryWaitTime() * 1000);

            try {
                log.info("第二次执行监控mongodb是否可用任务");
                MongoClientURI mongoClientUri = new MongoClientURI(mongodb.getUri());
                String database = mongoClientUri.getDatabase();
                client = new MongoClient(mongoClientUri);
                MongoIterable<String> strings = client.listDatabaseNames();
                for(String dataBaseName : strings){
                    if(dataBaseName.equals(database)){
                        ifHaveDataBase = Boolean.TRUE;
                        log.info("mongodb连接成功");
                        break;
                    }
                }

                if(ifHaveDataBase){
                    log.info("mongodb连接成功");
                }else{
                    throw new Exception("Mongodb连接失败");
                }
            }catch (Exception e1) {
                if(client != null){
                    client.close();
                    client = null;
                }

                log.warn("监控mongodb是否可用任务出现问题,原因:[{}],待{}秒后重试", e1.toString(), timeSetConfig.getRetryWaitTime());
                Thread.sleep(timeSetConfig.getRetryWaitTime() * 1000);

                try {
                    log.info("第三次执行监控mongodb是否可用任务");
                    MongoClientURI mongoClientUri = new MongoClientURI(mongodb.getUri());
                    String database = mongoClientUri.getDatabase();
                    client = new MongoClient(mongoClientUri);
                    MongoIterable<String> strings = client.listDatabaseNames();
                    for(String dataBaseName : strings){
                        if(dataBaseName.equals(database)){
                            ifHaveDataBase = Boolean.TRUE;
                            log.info("mongodb连接成功");
                            break;
                        }
                    }

                    if(ifHaveDataBase){
                        log.info("mongodb连接成功");
                    }else{
                        throw new Exception("Mongodb连接失败");
                    }
                }catch (Exception e2) {
                    if(client != null){
                        client.close();
                        client = null;
                    }

                    log.warn("监控mongodb是否可用任务出现问题,原因:[{}],mongodb连接失败", e2.toString());
                    message = e2.toString();
                }
            }
        }finally {
            if(client != null){
                client.close();
                client = null;
            }
        }

        if(!Strings.isNullOrEmpty(message)){
            if(message.length() > 100){
                message = message.substring(0, 100);
            }
        }

        return message;
    }
}